package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.dto.ReservationPageDto;
import com.zzyl.nursing.vo.ReservationCountByTimeVo;
import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 预约信息表Service业务层处理
 * 
 * @author Tomorrow
 * @date 2025-01-10
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息表
     * 
     * @param id 预约信息表主键
     * @return 预约信息表
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return reservationMapper.selectById(id);
    }

    /**
     * 查询预约信息表列表
     * 
     * @param reservation 预约信息表
     * @return 预约信息表
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息表
     * 
     * @param reservation 预约信息表
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        Long userId = UserThreadLocal.getUserId();
        reservation.setCreateBy(String.valueOf(userId));
        reservation.setUpdateBy(String.valueOf(userId));
        reservation.setStatus(0);

        try {
            return save(reservation)? 1:0;
        } catch (Exception e) {
            throw new BaseException("不能重复预约哦");
        }

    }

    /**
     * 修改预约信息表
     * 
     * @param reservation 预约信息表
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return reservationMapper.updateReservation(reservation);
    }

    /**
     * 批量删除预约信息表
     * 
     * @param ids 需要删除的预约信息表主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return reservationMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除预约信息表信息
     * 
     * @param id 预约信息表主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return reservationMapper.deleteById(id);
    }

    /**
     * 小程序端的预约分页查询
     *
     * @param reservationPageDto
     * @return
     */
    @Override
    public TableDataInfo<Reservation> findReservationByPage(ReservationPageDto reservationPageDto) {

        //先判断是否登录
        Long userId = UserThreadLocal.getUserId();

        if (ObjectUtil.isEmpty(userId)){
            throw new BaseException("请先登录");
        }

        //创建分页对象
        Page<Reservation> page = new Page<>(reservationPageDto.getPageNum(), reservationPageDto.getPageSize());

        //条件查询
        LambdaQueryWrapper<Reservation> queryWrapper = Wrappers.lambdaQuery(Reservation.class)
                .like(reservationPageDto.getStatus() != null, Reservation::getStatus, reservationPageDto.getStatus());

        //执行查询语句
        page = page(page,queryWrapper);

        //调用方法封装数据
        return getTableDataInfo(page);


    }

    /**
     * 小程序取消预约
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelReservation(Long id) {

        Reservation reservation = selectReservationById(id);

        if (ObjectUtil.isEmpty(reservation)){
            throw  new BaseException("预约不存在");
        }

        Integer count = getCancelledReservationCount();

        if (count <=3){
            reservation.setStatus(2);

            //获取当前登录用户的Id
            Long updateBy = UserThreadLocal.getUserId();

            //将当前修改人的ID存入到reservation中
            reservation.setUpdateBy(String.valueOf(updateBy));
            updateReservation(reservation);

        }



    }

    /**
     * 微信小程序查询当天取消预约数量
     */
    @Override
    public Integer getCancelledReservationCount() {

        // 获取当前时间并转换为 LocalDateTime
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);

        // 设置开始时间为当天凌晨
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();

        // 设置结束时间为次日凌晨，即当天的最后一刻
        LocalDateTime endTime = startTime.plusDays(1);

        //获取当前登录用户的Id
        Long updateBy = UserThreadLocal.getUserId();

        Long count = reservationMapper.selectCount(Wrappers.<Reservation>lambdaQuery()
                .eq(Reservation::getUpdateBy,updateBy)
                .eq(Reservation::getStatus, 2)
                .le(Reservation::getUpdateTime, endTime)
                .gt(Reservation::getUpdateTime, startTime));

        return Math.toIntExact(count);

        /* Integer count = reservationMapper.getCancelledReservationCount(updateBy,startTime,endTime);

        return count;*/
    }

    /**
     * 封装分页结果
     * @param page
     * @return
     */
    private TableDataInfo<Reservation> getTableDataInfo(Page<Reservation> page) {

        TableDataInfo<Reservation> reservationTableDataInfo = new TableDataInfo<>();
        reservationTableDataInfo.setRows(page.getRecords());
        reservationTableDataInfo.setTotal(page.getTotal());
        reservationTableDataInfo.setCode(HttpStatus.SUCCESS);
        reservationTableDataInfo.setMsg("查询成功");
        return reservationTableDataInfo;
    }

    /**
     * 查询每个时间段剩余预约次数
     *
     * @param time
     * @return
     */
    @Override
    public List<ReservationCountByTimeVo> countByTime(Long time) {
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);

        LocalDateTime startTime = localDateTime.toLocalDate().atStartOfDay();

        LocalDateTime endTime = startTime.plusDays(1);


        List<ReservationCountByTimeVo> list = reservationMapper.countByTime(startTime,endTime);
        return list;
    }



    /**
     * 定时更新预约状态
     */
    @Override
    public void updateReservationStatus() {

        //获取当前时间减30分钟的时间,和预约时间进行比对
        List<Reservation> reservations = list(Wrappers.<Reservation>lambdaQuery()
                .lt(Reservation::getTime, LocalDateTime.now().minusMinutes(30))
                .eq(Reservation::getStatus, 0));

        //设置状态已过期
        reservations.forEach(reservation -> reservation.setStatus(3));

        //批量更新
        updateBatchById(reservations);

    }
}
